<?php

class Application_Model_AclResources extends Zend_Db_Table {
	protected $_name = 'acl_resource';
	protected $_primary = 'id';
	protected $_sequence = true;
	
	public function getAclResources($conditions = null) {
		$sql = $this->select ();
		
		if ($conditions) {
			if (is_array ( $conditions )) {
				foreach ( $conditions as $k => $v ) {
					$sql->where ( $k, $v );
				}
			} else {
				$sql->where ( $conditions );
			}
		}
		return $this->fetchAll ( $sql )->toArray();
	}
	
	/**
	 * Generate acl_resource table with all modules, module:controllers, module:controller:actions
	 * to be used forwarth in the application
	 *
	 */
	public function generateResourceTable() {
		// get modules controlers actions
		$existingResources = array ();
		$modules = Zend_Controller_Front::getInstance()->getControllerDirectory();
		
		foreach ($modules as $k => $v) {
			$existingResources[] = $k;
			// removed getcwd(). DIRECTORY_SEPARATOR .
			$dirRes = opendir($v);
			$files = array();
			while($file = readdir($dirRes)) {
				if($file != '.' && $file != '..' && $file != '.svn' && !is_dir($file)) {
					$controllerName = str_replace('Controller.php', '', $file);
					$existingResources[] = $k.':'.strtolower($controllerName);
					if($k != 'default') {
						$className = ucfirst(strtolower($k)).'_'.ucfirst($controllerName).'Controller';
					} else {
						$className = ucfirst($controllerName).'Controller';
					}

					$actions = array();
					$actions = get_class_methods($className);
					if ( is_array($actions) ){
						foreach($actions as $value) {
							if(strstr($value, 'Action')) {
								$action = str_replace('Action', '', $value);
								# work around in absence of lcfirst
								$action[0] = strtolower($action[0]);
								$action = (string) $action;
								# end work around
								$action = preg_replace(array('/[A-Z]+/'), array('-$0'), $action);
								$action = strtolower($action);
								$existingResources[] = $k.':'.strtolower($controllerName).':'.$action;
							}
						}
					}
				}
			}
		}
		
		$storedResources = $this->fetchAll()->toArray();
		$databaseResources = array();
		foreach($storedResources as $value) {
			$databaseResources[] = $value['resource'];
		}
		
		$newResources = array_diff($existingResources, $databaseResources);
		foreach($newResources as $value) {
			$data= array('resource' => $value);
			$this->insert($data);
		}
	}
	
	
	/**
	 * Make the select for using with paginator
	 *
	 * @return (Zend_DB_Table_Select) $sql
	 */
	public function getPaginatorItems($where = null, $order = array('field' => null, 'type' => 'ASC')) {
		$sql = $this->select();
		# Customize your SQL here by adding join and where clauses
		
		$safeSql = clone($sql);
		if ($where != null) {
			$sql->where ( $where );
		}
		if(empty($order['type'])) {
			$order['type'] = 'ASC';
		}
		if($order && $order['field']) {
			$sql->order( array($order ['field'].' '.$order ['type']) );
		}
		try {
			//Zend_Debug::dump($sql->__toString());
			$dbAdapter = Zend_Registry::get('dbAdapter');
			$dbAdapter->query($sql);
			return $sql;
		} catch(Zend_Exception $e) {
			//Zend_Debug::dump($safeSql->__toString());
			Zend_Controller_Action_HelperBroker::getHelper('FlashMessenger')->addMessage('We are sorry but for the moment the filter is broken. You can still use this listing but without the use of the filter from. <a href="http://proiecte.dev/framework/newticket">(report this bug)</a>');
			return $safeSql;
		}
		return $sql;
	}
	
}